package com.luom.fsp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.luom.fsp.annotation.AuthCheck;
import com.luom.fsp.common.BaseResponse;
import com.luom.fsp.common.DeleteRequest;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.common.ResultUtils;
import com.luom.fsp.constant.UserConstant;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.model.dto.user.*;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.LoginUserVO;
import com.luom.fsp.model.vo.UserVO;
import com.luom.fsp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    // region 登录相关

    // 管理员登录
    @PostMapping("/adminLogin")
    public BaseResponse<String> adminLogin(@RequestBody AdminLoginRequest adminLoginRequest) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(adminLoginRequest), ErrorCode.PARAMS_ERROR, "请重新登录");
        String token = userService.adminLogin(adminLoginRequest);
        return ResultUtils.success(token);
    }

    // 注册
    @PostMapping("/register")
    public BaseResponse<Boolean> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.userRegister(userRegisterRequest));
    }


    // 微信登录
    @PostMapping("/wxLogin")
    public BaseResponse<String> login(@RequestBody UserLoginRequest loginRequest) throws JsonProcessingException {

        String token = userService.wxLogin(loginRequest);

        // 返回用户信息和 token
        return ResultUtils.success(token);
    }

    // 微信用户登录
    @PostMapping("/userLogin")
    public BaseResponse<String> userLogin(@RequestBody AdminLoginRequest adminLoginRequest) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(adminLoginRequest), ErrorCode.PARAMS_ERROR, "请重新登录");
        String token = userService.userLogin(adminLoginRequest);
        return ResultUtils.success(token);
    }

    /*@PostMapping("/wxLogin")
    public BaseResponse<String> login(@RequestBody UserLoginRequest loginRequest) throws JsonProcessingException {
        String code = loginRequest.getCode();
        String encryptedData = loginRequest.getEncryptedData();
        String iv = loginRequest.getIv();

        if (code == null || code.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "code不能为空");
        }
        if (encryptedData == null || iv == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "加密数据不能为空");
        }

        // 获取微信会话信息
        WeixinSessionResponse sessionData = userService.getSessionKey(code);
        if (sessionData == null || sessionData.getSession_key() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "获取微信 session 失败");
        }

        String sessionKey = sessionData.getSession_key();
        String unionid = sessionData.getUnionid();
        String openid = sessionData.getOpenid();

        // 解密手机号
        String phoneNumber = userService.getPhoneNumber(encryptedData, sessionKey, iv);
        if (phoneNumber == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "解析手机号失败");
        }

        User user = userService.getOne(new QueryWrapper<User>().eq("phone", phoneNumber));
        if (user == null) {
            // 新用户注册
            user = new User();
            user.setPhone(phoneNumber);
            user.setOpenid(openid);
            user.setUnionid(unionid);
            userService.save(user);
        } else {
            if(user.getOpenid()==null){
                user.setOpenid(openid);
                userService.updateById(user);
            }
            if (user.getUnionid() == null){
                user.setUnionid(unionid);
                userService.updateById(user);
            }
        }

        // 生成 JWT token
        String token = JwtUtil.createToken(user);

        // 返回用户信息和 token
        return ResultUtils.success(token);
    }*/

    // 获取当前登录用户信息
    @GetMapping("/getLoginUser")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // 退出登录
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    // endregion


    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = userService.addUser(userAddRequest);
        return ResultUtils.success(id);
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
                                            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.updateUser(userUpdateRequest);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                   HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                       HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        // 参数校验
        boolean isValid =userService.checkUpdate(user);
        if (!isValid){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        userService.deleteUserToRedisAsync(user);
        return ResultUtils.success(true);
    }

    // endregion

}
